package com.able.concurrency.t2;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author abel.he
 * @data 2018/8/18 12:24
 * @describe 阻塞尝试锁
 */
public class Test2 {

    Lock lock = new ReentrantLock();

    void m() {
        try {
            lock.lock();
            for (int i = 0; i < 3; i++) {
                System.out.println(Thread.currentThread().getName() + " m()： " + i);
                TimeUnit.SECONDS.sleep(1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    void m1() {
        boolean isLock = false;
        try {
            //尝试锁 如果获取锁标记返回true
            //如果没有获取到锁标记 返回false
//            isLock = lock.tryLock();

            // 阻塞尝试所 阻塞参数代表的时长 尝试获取所标记
            // 如果超时 不等待 直接返回
            isLock = lock.tryLock(5, TimeUnit.SECONDS);
            if (isLock) {
                System.out.println("m1() synchronized");
            } else {
                System.out.println("m1() unsynchronized");
            }
        } catch (Exception e) {
        } finally {
            if (isLock) {
                // 尝试锁在解除搜标记的时候，一定要判断是否获取到锁标记
                // 如果当前线程没有获取到锁标记 .unlock() 方法会抛出异常
                lock.unlock();
                System.out.println("m1() end");
            }

        }
    }

    public static void main(String[] args) {
        final Test2 test2 = new Test2();
        new Thread(new Runnable() {
            public void run() {
                test2.m();
            }
        }).start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(new Runnable() {
            public void run() {
                test2.m1();
            }
        }).start();
    }

}
